package com.handler;

import com.message.ChatLoginOutMessage;
import com.session.ChatServerContext;
import com.session.ChatServerContextFactory;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 罗俊华
 * @date 2021/8/30 - 9:07 上午
 */
@Slf4j
@ChannelHandler.Sharable
public class ChatLoginOutHandler extends SimpleChannelInboundHandler<ChatLoginOutMessage> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatLoginOutMessage msg) throws Exception {
        clearDisconnectedChannel(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String name = ChatServerContextFactory.getInstance().getUserNameByChannel(ctx.channel());
        log.debug("{}已正常的断开连接", name);
        this.clearDisconnectedChannel(ctx);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        String name = ChatServerContextFactory.getInstance().getUserNameByChannel(ctx.channel());
        log.debug("{}已异常的断开连接", name);
        this.clearDisconnectedChannel(ctx);
    }


    private void clearDisconnectedChannel(ChannelHandlerContext ctx) {
        ChatServerContext chatServerContext = ChatServerContextFactory.getInstance();

        String userNameByChannel = chatServerContext.getUserNameByChannel(ctx.channel());

        chatServerContext.deleteChannelByUserName(userNameByChannel);

        ctx.channel().close();

        log.debug("{}请求断开连接", userNameByChannel);

        ctx.channel().closeFuture().addListener((ChannelFuture channelFuture) -> {
            log.debug("{}的连接已断开", userNameByChannel);
        });

    }
}
